<?php

/**
 * 微信网页开发API
 * Class WxWebApi
 */
class WxWebApi
{

    /**
     * 获取AccessToken，失败返回false
     * @param string $code
     * @return bool|string
     */
    public static function getAccessToken($code)
    {
        $api = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . WxConfig::APPID . '&secret=' . WxConfig::APPSECRET . '&code=' . $code . '&grant_type=authorization_code';
        $result = json_decode(WxFunction::curlGet($api), TRUE);
        if (is_array($result) && !empty($result['access_token'])) return $result;

        return FALSE;
    }

    /**
     * 获取code
     * @param string $scope
     * @param string $redirectUrl
     * @param string $callbackUrl
     */
    public static function getCode($scope, $redirectUrl, $callbackUrl)
    {
        header('Location: ' . 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . WxConfig::APPID . '&redirect_uri=' . $redirectUrl . '&response_type=code&scope=' . $scope . '&state=' . $callbackUrl . '#wechat_redirect');
        exit();
    }

    /**
     * 获取用户信息
     * @param string $access_token
     * @param string $openid
     * @return bool|array
     */
    public static function getInfo($access_token, $openid)
    {
        $api = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $data = json_decode(WxFunction::curlGet($api), TRUE);
        if (is_array($data) && isset($data['openid'])) return $data;
        return FALSE;
    }
}